package com.hbnu.service;

import com.hbnu.entity.UserFile;
import com.hbnu.enums.Status;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hbnu.tools.PrintTool.printSelectList;
import static com.hbnu.tools.PrintTool.println;
import static com.hbnu.web.Client.idUserFileMap;

public class SelectService extends AbstractFunctionService {
    public SelectService() {
        cmdMap.put("selectvid",this::selectvid);
        cmdMap.put("selectimg",this::selectimg);
        cmdMap.put("selectdoc",this::selectdoc);

        oneMap.put("select",this::select);
        oneMap.put("selectvid",this::selectvid);
        oneMap.put("selectimg",this::selectimg);
        oneMap.put("selectdoc",this::selectdoc);
    }

    //搜索
    private void selectvid(){
        select0("vid");
    }
    private void selectimg(){
        select0("img");
    }
    private void selectdoc(){
        select0("doc");
    }
    //selectvid id
    private void selectvid(String arg){
        selectId(arg,"vid");
    }
    private void selectimg(String arg){
        selectId(arg,"img");
    }
    private void selectdoc(String arg){
        selectId(arg,"doc");
    }
    private List<UserFile> getTypeList(String type){
        Set<String> types = Status.typeMap.get(type);
        Collection<UserFile> values = idUserFileMap.values();
        List<UserFile> collect = values.stream().filter(file -> {
            int i = file.getFname().lastIndexOf(".");
            if(i==-1) return false;
            String postfix = file.getFname().substring(i + 1).toUpperCase();
            return types.contains(postfix);
        }).collect(Collectors.toList());
        if(collect.isEmpty()) return null;
        return collect;

    }
    private void select0(String type){
        List<UserFile> collect=getTypeList(type);
        if(null==collect) return;
        printSelectList(collect);

    }
    private void selectId(String arg,String type){
        if(!"id".equals(arg)) return;
        List<UserFile> collect=getTypeList(type);
        if(null==collect) return;
        String text = collect.stream()
                .map(UserFile::getFid)
                .map(String::valueOf) // 将 Integer 转为 String
                .collect(Collectors.joining(","));
        println(text);
    }

    //select 模糊搜索
    private void select(String s) {
        Collection<UserFile> userFileCollection=idUserFileMap.values();
        List<UserFile> collect = userFileCollection.stream()
                .filter(file -> file.getFname().toLowerCase().contains(s))
                .collect(Collectors.toList());
        if(collect.isEmpty()) return;
        printSelectList(collect);
    }
}
